<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-left">
      <div class="jsbos-common-title">
        <h2>素材目录</h2>
      </div>
      <el-tree
        :data="treeData"
        :props="treeProps"
        default-expand-all
        highlight-current
        ref="treeBox"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        :default-checked-keys="['-1']"
        class="jsbos-common-el-tree"
        node-key="id"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <i :class="data.icon"></i>
          <span class="text">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>

    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item label="素材名称">
              <el-input
                v-model="query.name"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="4">
              <el-form-item label="类型">
                <el-select v-model="query.type" placeholder="请选择" clearable>
                  <el-option
                    v-for="(item, index) in typeOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="状态">
                <el-select
                  v-model="query.enabledMark"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in enabledMarkOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="3">
            <el-form-item label="">
              <el-checkbox v-model="query.myCreated" @change="search()"
                >只看我创建的</el-checkbox
              >
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
              <el-button
                type="text"
                icon="el-icon-arrow-down"
                @click="showAll = true"
                v-if="!showAll"
              >
                展开
              </el-button>
              <el-button
                type="text"
                icon="el-icon-arrow-up"
                @click="showAll = false"
                v-else
              >
                收起
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="openUploadSource()"
              >上传文件
            </el-button>
          </div>
          <div class="jsbos-common-head-right">
            <el-link
              icon="JSBOS-common-head-icon"
              :underline="false"
              @click="reset()"
            >
              共{{ total }}个素材
            </el-link>
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screen-full isContainer />
            <el-tooltip effect="dark" content="列设置" placement="top">
              <el-link
                icon="icon-ym icon-ym-options jsbos-common-head-icon"
                :underline="false"
                @click="() => this.$refs.jsbosTableRef.showDrawer()"
              />
            </el-tooltip>
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="list"
          ref="jsbosTableRef"
          @sort-change="sortChange"
          border
        >
          <el-table-column
            prop="catalogId"
            label="资源目录"
            width="150"
            align="left"
          />
          <el-table-column prop="name" label="素材名称" width="0" align="left">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="previewSource(scope.row)"
                >{{ scope.row.name }}</el-link
              >
            </template>
          </el-table-column>
          <el-table-column label="类型" width="100" prop="type" align="center">
            <template slot-scope="scope">
              {{ scope.row.type | dynamicText(typeOptions) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="fileSize"
            label="大小"
            width="100"
            align="right"
          />
          <el-table-column prop="creatorUserId" label="创建用户" width=100"
          align="center" />
          <el-table-column
            prop="creatorTime"
            label="创建时间"
            width="150"
            align="center"
          />
          <el-table-column
            label="状态"
            width="100"
            prop="enabledMark"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.enabledMark | dynamicText(enabledMarkOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)"
                >编辑
              </el-button>
              <el-button
                type="text"
                class="jsbos-table-delBtn"
                @click="handleDel(scope.row.id)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JSBOS-Form v-if="formVisible" ref="JSBOSForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <Detail
      v-if="detailVisible"
      ref="Detail"
      @refresh="detailVisible = false"
    />
    <select-source
      v-if="selectSourceVisible"
      :tabOnlyUpload="true"
      tabActiveName="upload"
      @selectComplete="refresh"
      ref="selectSourceRef"
    >
    </select-source>
    <Preview :visible.sync="previewVisible" :file="activeFile" />
  </div>
</template>

<script>
import request from "@/utils/request";
import Preview from "@/components/Generator/components/Upload/Preview";
import JSBOSForm from "./Form";
import SelectSource from "./SelectSource";
import ExportBox from "./ExportBox";
import Detail from "./Detail";
import { PreviewFile } from "@/api/common";

export default {
  name: "TemsSource",
  components: { JSBOSForm, ExportBox, Detail, SelectSource, Preview },
  data() {
    return {
      selectSourceVisible: false,
      showAll: false,
      detailVisible: false,
      previewVisible: false,
      activeFile: {},
      query: {
        name: undefined,
        catalogId: undefined,
        type: undefined,
        enabledMark: undefined,
        myCreated: false,
      },
      treeProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [
        { prop: "catalogId", label: "资源目录" },
        { prop: "name", label: "素材名称" },
        { prop: "type", label: "类型" },
        { prop: "size", label: "大小" },
        { prop: "creatorUserId", label: "创建用户" },
        { prop: "creatorTime", label: "创建时间" },
        { prop: "enabledMark", label: "状态" },
      ],
      treeData: [],
      treeActiveId: "-1",
      treeActiveName: "全部",
      catalogIdOptions: [],
      catalogIdProps: {
        label: "fullName",
        value: "id",
        children: "children",
      },
      typeOptions: [
        { name: "视频", id: "视频" },
        { name: "音频", id: "音频" },
        { name: "文档", id: "文档" },
        { name: "图片", id: "图片" },
      ],
      typeProps: {
        label: "name",
        value: "id",
      },
      enabledMarkOptions: [{ fullName: "正常", id: "10" }],
      enabledMarkProps: {
        label: "fullName",
        value: "id",
      },
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.initData();
    this.getTreeView();
    this.gettypeOptions();
    this.getcatalogIdOptions();
  },
  methods: {
    openUploadSource() {
      this.selectSourceVisible = true;
      this.$nextTick(() => {
        this.$refs.selectSourceRef.initData();
      });
    },
    previewSource(item) {
      this.activeFile = JSON.parse(item.fileJson);
      this.previewVisible = true;
    },
    getcatalogIdOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "559344335821209861",
        })
        .then((res) => {
          this.catalogIdOptions = res;
        });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    getTreeView() {
      request({
        url: "/api/course/TemsSourceCatalog/Selector",
        method: "get",
      }).then((res) => {
        let data = [];
        let topItem = {
          name: "全部",
          hasChildren: true,
          id: "-1",
          children: res.data.list,
        };
        this.treeData = data.concat(topItem);
        this.loading = false;
      });
    },
    getNodePath(node) {
      let fullPath = [];
      const loop = (node) => {
        if (node.level) fullPath.unshift(node.data);
        if (node.parent) loop(node.parent);
      };
      loop(node);
      return fullPath;
    },
    handleNodeClick(data, node) {
      this.treeActiveId = data.id;
      this.treeActiveName = data.name;
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.query.catalogId = data.id;
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      };
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/course/TemsSource/getList`,
        method: "post",
        data: _query,
      }).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/course/TemsSource/${id}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, isDetail);
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/course/TemsSource/Actions/Export`,
        method: "GET",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        this.jsbos.downloadFile(res.data.url);
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.query.myCreated = false;
      this.search();
    },
  },
};
</script>
<style>
.jsbos-common-head-right-total {
  width: 30px;
}
</style>
